package app_param

import (
	"github.com/gin-gonic/gin"
)

func AppParamMiddleware() gin.HandlerFunc {
	return func(context *gin.Context) {
		version := defaultAnyParam(context, "v", "")
		from := defaultAnyParam(context, "f", "")

		appParam := &AppParam{
			From:    from,
			Version: version,
		}

		context.Set("appParam", appParam)
	}
}

func anyParam(context *gin.Context, key string) (value string) {
	if value = context.PostForm(key); len(value) != 0 {
		return
	}
	if value = context.Query(key); len(value) != 0 {
		return
	}
	if value = context.Param(key); len(key) != 0 {
		return
	}
	return
}

func defaultAnyParam(context *gin.Context, key string, defaultValue string) (value string) {
	if value = anyParam(context, key); len(value) != 0 {
		return
	}
	return defaultValue
}
